<?php
/**
 * 微信接入校验
 * wechat php test
 */


define("TOKEN", "abc");
$chat = new weiChat();
$chat->getToken();
$chat->createMenu(); 
exit;
isset($_GET['echostr']) ? $chat->valid():$chat->responseMsg();

class weiChat
{
	private $appID = 'wx0ce39c348caeb7b3';
	private $appsecret = '98d689f87514508e54d084b0c289a38e';
	private $reqURL = 'https://api.weixin.qq.com/cgi-bin/';// 请求URL
	private $token = 'SWdS4n5eci2I6cQfASJxzJiA4J2WqwLNC_Oz9zniHGduOzSCF29-P9zc32lt1y_86XxG_6awnIoqnvLxInx9Gg';
	
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
	// 获取 ACCESS_TOKEN
	public function getToken(){
		$url=$this->reqURL.'token?grant_type=client_credential&appid='.$this->appID.'&secret='.$this->appsecret;
		echo file_get_contents($url);
	}
	
	// 获取交互数据
	public function getPost(){
		
	}
	// 用户交互
    public function responseMsg(){
		$post = $GLOBALS["HTTP_RAW_POST_DATA"];
		err($post);
        $postData  = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);
        // if(empty($postData)) exit("");
		$fromUsername = (string)$postData->FromUserName;
		$toUsername = (string)$postData->ToUserName;
		$msgType = (string)$postData->MsgType;
		
		$time = time();
		$textTpl = $this->getResponseTpl();
		$contentStr = "Welcome to wechat world.....!";
		if($msgType=='event' && (string)$postData->Event=='CLICK'){
			$contentStr="aaaa1";
			$this->responseView($fromUsername,$toUsername,$time,'http://www.12301.cc');
			// exit;
			$msgType='text';
		}	

		if($msgType=='event'&&(string)$postData->Event=='VIEW'){
			$this->responseView($fromUsername,$toUsername,$time,'http://www.12301.cc');
		}
		err(sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr));
		$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
		echo $resultStr;
    }
	
	public function getResponseTpl(){
		$tpl=<<<template
		<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[%s]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
		</xml>
template;
		return $tpl;
	}
	public function responseView($to,$from,$time,$url){
		$tpl=<<<template
		<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[event]]></MsgType>
			<Event><![CDATA[VIEW]]></Event>
			<EventKey><![CDATA[%s]></EventKey>
		</xml>
template;
		$resultStr = sprintf($tpl, $to, $from, $time, $url);
		err($resultStr);
		echo $resultStr;
		exit;
	}
	// 创建菜单按钮
	public function createMenu(){
		$url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->token;
		$menu = json_encode($menu);
		$reUrl=urlencode("http://www.12301.cc/fx_app/index.php");
		$s=<<<h
		{
		 "button":[
		 {	
			  "type":"click",
			  "name":"今日歌曲",
			  "key":"V1001_TODAY_MUSIC"
		  },
		  {
			   "type":"click",
			   "name":"歌手简介",
			   "key":"INODE"
		  },
		  {
			   "name":"菜单",
			   "sub_button":[
			   {	
				   "type":"view",
				   "name":"我要订票",
				   "url":"http://www.12301.cc/abc/weiChatBind.html"
				},
				{
				   "type":"view",
				   "name":"视频",
				   "url":"http://www.ybxtw.com/"
				},
				{
				   "type":"view",
				   "name":"赞一下我们",
				   "url":"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxea5087a9ebe15e47&redirect_uri=$reUrl&response_type=code&scope=snsapi_base&state=123#wechat_redirect"
				}]
		   }]
		 }
h;
		err("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxea5087a9ebe15e47&redirect_uri=$reUrl&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
		echo self::raw_post($url,$s);
	}
	
	// 执行 CRUL ，并返回结果
	public static function executeCurl($url, $option){
		$ch = curl_init($url);
		return curl_exec($ch);
	}
	
	public static function raw_post($url,$data){
		$ch = curl_init(); 
		curl_setopt($ch, CURLOPT_POST, 1); 
		curl_setopt($ch, CURLOPT_HEADER, 0); 
		curl_setopt($ch, CURLOPT_URL,$url); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		return curl_exec($ch);
	}

    private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		return ($tmpStr == $signature) ? true:false;
	}

}

function err($txt,$file='abc/a_debug.txt'){
	$fp = fopen($file,"a");
	flock($fp, LOCK_EX) ;
	fwrite($fp,$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}
?>